package com.jiangtai.training.ui.map
import android.annotation.SuppressLint
import android.content.Context
import android.content.LoRaManager
import android.content.SndData
import android.os.Handler
import android.util.Log
import com.cld.mapapi.map.CldMap
import com.cld.mapapi.map.MapStatusType
import com.cld.mapapi.map.MarkerOptions
import com.cld.mapapi.map.PolyLineOptions
import com.cld.mapapi.model.LatLng
import com.cld.nv.location.CldCoordUtil
import com.cld.nv.map.overlay.impl.MapMarker
import com.cld.nv.map.overlay.impl.MapPolyLine
import com.jiangtai.training.R
import com.jiangtai.training.base.BaseActivity
import com.jiangtai.training.bean.LocationInfoBean
import com.jiangtai.training.constant.Constant
import com.jiangtai.training.event.RefreshLocEvent
import com.jiangtai.training.util.CrcUtil
import com.jiangtai.training.util.HexUtil
import com.jiangtai.training.util.Preference
import kotlinx.android.synthetic.main.activity_map.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.litepal.LitePal
import showToast
import kotlin.math.log

/**
 * Created by heCunCun on 2021/3/22
 */
class MapActivity : BaseActivity() {
    override fun useEventBus(): Boolean =true
    //定位点坐标集合
 //   private var line: MapPolyLine? = null
  //  private var markes:MapMarker ? = null
    private var markers = mutableListOf<MapMarker>()
    private var pointList = mutableListOf<LatLng>()
    private var center :LatLng?= null
    private var cldMap: CldMap? = null
    private var personId = ""
    private var projectId = ""
    private var taskId = ""
    private var phoneId: String by Preference(Constant.PHONE_ID, "")
    override fun attachLayoutRes(): Int = R.layout.activity_map

    override fun initData() {
        refreshData()
    }
    private fun refreshData() {
//        if (line != null) {
//            cldMap?.removeOverlay(line)
//            pointList.clear()
//        }
        if (markers .size>0) {
            markers.forEach {
                cldMap?.removeOverlay(it)
            }
            pointList.clear()
        }

        //查位置数据表  显示轨迹
        val locList = LitePal.where("taskId=? and personId=? and projectId=?", taskId, personId, projectId)
                .find(LocationInfoBean::class.java)
        Log.e("HTHT","刷新心率locList==${locList.size}, taskId=$taskId, personId=$personId, projectId=$projectId")
        if (locList.isNotEmpty()){
            tv_heart_rate.text = locList.last().heartRate.toString()
        }

        for (loc in locList){
            pointList.add(CldCoordUtil.wgs84ToCLDEx(loc.lat,loc.lng,0.0))
        }

//        line = (cldMap?.addOverlay(
//            PolyLineOptions().color(resources.getColor(R.color.color_blue_2979FF)).points(pointList).width(10).dottedLine(
//                true
//            )
//        )) as MapPolyLine


        for (position in pointList){
            val marker = (cldMap?.addOverlay(
                MarkerOptions().position(position).icon(resources.getDrawable(R.mipmap.ic_position))
            )) as MapMarker
            markers.add(marker)
        }


       cldMap?.zoomToSpan(pointList) // 缩放到合适比例，将传入的点坐标都显示出来
    }

    override fun onPause() {
        super.onPause()
        mapView.onPause()
//        if (line != null) {
//            cldMap?.removeOverlay(line)
//        }
        if (markers .size>0) {
            markers.forEach {
                cldMap?.removeOverlay(it)
            }
            pointList.clear()
        }
    }
    private fun setCenter() {
        if (center == null) {
            center = CldCoordUtil.wgs84ToCLDEx(30.867198,120.102398,0.0)
            Log.e("center","center = ${center}")
        }
        cldMap?.setMapCenter(center)
    }
    override fun onResume() {
        super.onResume()
        mapView.onResume()
        setCenter()
        refreshData()
    }

    override fun onDestroy() {
        super.onDestroy()
        switchReport(false)
        report = false
        mapView.destroy()
    }
    private var report = true
    private var handler = Handler()
    override fun initView() {
        val name = intent.getStringExtra("name")
        tv_name.text = "学员轨迹:$name"
        personId = intent.getStringExtra("personId")
        projectId = intent.getStringExtra("projectId")
        taskId = intent.getStringExtra("taskId")
        switchReport(true)
        cldMap = mapView.map
        cldMap?.mapDisplayMode = 2
        cldMap?.mapViewMode = MapStatusType.MAP_TYPE_2DNorth
        cldMap?.setLocationIconEnabled(false)//清除中心点
        setCenter()
        handler.postDelayed(Runnable {
            Thread{
                while (report){
                    askReport()
                    Thread.sleep(5000)
                }
            }.start()
        },5000)


    }

    override fun initListener() {
        iv_back.setOnClickListener {
            finish()
        }
        iv_send.setOnClickListener {
            //发上报位置
        }
    }


    @SuppressLint("WrongConstant")
    private fun switchReport(start :Boolean){
        val switchByte = if (start){ 0x01.toByte()} else{ 0x02.toByte()}
        val projectBytes = HexUtil.decodeHex(projectId.toCharArray())
        val personIdBytes = HexUtil.decodeHex(personId.toCharArray())
        val loRaManager = getSystemService(Context.LORA_SERVICE) as LoRaManager
        val bytes = arrayOf(0xE7.toByte(), 0xEA.toByte(),0x54.toByte(),20,
            switchByte,
            projectBytes[0],
            projectBytes[1],
            (phoneId.toInt() and 0xff).toByte(),
            personIdBytes[0], personIdBytes[1], personIdBytes[2], personIdBytes[3], personIdBytes[4], personIdBytes[5],
            personIdBytes[6], personIdBytes[7], personIdBytes[8], personIdBytes[9], personIdBytes[10], personIdBytes[11],
            personIdBytes[12], personIdBytes[13], personIdBytes[14], personIdBytes[15],
            0,0)
        val calculateCrc = CrcUtil.Calculate_Crc(bytes.toByteArray(), 0, 24)
        val shortToBytes = HexUtil.shortToBytes(calculateCrc)
        bytes[24] = shortToBytes[0]
        bytes[25] = shortToBytes[1]
        val formatHexString = HexUtil.formatHexString(bytes.toByteArray(), true)
        Log.e("SEND", "SEND==>$formatHexString")
        //showToast("SEND==>$formatHexString")
        val sndData = SndData(bytes.toByteArray(), bytes.size)
        loRaManager.sendContent(sndData)
    }

    @SuppressLint("WrongConstant")
    private fun askReport(){
        val switchByte =  0x03.toByte()
        val projectBytes = HexUtil.decodeHex(projectId.toCharArray())
        val personIdBytes = HexUtil.decodeHex(personId.toCharArray())
        val loRaManager = getSystemService(Context.LORA_SERVICE) as LoRaManager
        val bytes = arrayOf(0xE7.toByte(), 0xEA.toByte(),0x54.toByte(),20,
                switchByte,
                projectBytes[0],
                projectBytes[1],
                (phoneId.toInt() and 0xff).toByte(),
                personIdBytes[0], personIdBytes[1], personIdBytes[2], personIdBytes[3], personIdBytes[4], personIdBytes[5],
                personIdBytes[6], personIdBytes[7], personIdBytes[8], personIdBytes[9], personIdBytes[10], personIdBytes[11],
                personIdBytes[12], personIdBytes[13], personIdBytes[14], personIdBytes[15],
                0,0)
        val calculateCrc = CrcUtil.Calculate_Crc(bytes.toByteArray(), 0, 24)
        val shortToBytes = HexUtil.shortToBytes(calculateCrc)
        bytes[24] = shortToBytes[0]
        bytes[25] = shortToBytes[1]
        val formatHexString = HexUtil.formatHexString(bytes.toByteArray(), true)
        Log.e("SEND", "SEND==>$formatHexString")
        //showToast("SEND==>$formatHexString")
        val sndData = SndData(bytes.toByteArray(), bytes.size)
        loRaManager.sendContent(sndData)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshLoc(e: RefreshLocEvent){
        Log.e("HTHT","刷新心率")
        refreshData()
    }
}